package com.example.webapp.controller;

import com.example.webapp.entity.RequestGroup;
import com.example.webapp.model.Project;
import com.example.webapp.repository.ProjectRepository;
import com.example.webapp.service.RequestGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/request-groups")
public class RequestGroupController {

    @Autowired
    private RequestGroupService requestGroupService;

    @Autowired
    private ProjectRepository projectRepository;

    @GetMapping
    public ResponseEntity<List<RequestGroup>> getGroups(@RequestParam Long projectId) {
        try {
            Project project = projectRepository.findById(projectId)
                    .orElseThrow(() -> new RuntimeException("Project not found"));
            return ResponseEntity.ok(requestGroupService.getGroupsByProjectId(projectId));
        } catch (Exception e) {
            log.error("Error getting groups for project {}: {}", projectId, e.getMessage());
            throw e;
        }
    }

    @PostMapping
    public ResponseEntity<RequestGroup> createGroup(@RequestBody Map<String, Object> request) {
        try {
            String name = (String) request.get("name");
            Long projectId = ((Number) request.get("projectId")).longValue();
            
            if (projectId == null) {
                return ResponseEntity.badRequest().body(null);
            }

            Project project = projectRepository.findById(projectId)
                    .orElseThrow(() -> new RuntimeException("Project not found"));
            
            String groupName = name != null && !name.trim().isEmpty() ? name : "未命名分组";
            RequestGroup savedGroup = requestGroupService.createGroup(groupName, projectId);
            
            log.info("Successfully created group: {}", savedGroup);
            return ResponseEntity.ok(savedGroup);
        } catch (Exception e) {
            log.error("Error creating request group: ", e);
            throw e;
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<RequestGroup> updateGroup(@PathVariable Long id, @RequestBody RequestGroup requestGroup) {
        try {
            return ResponseEntity.ok(
                requestGroupService.updateGroup(id, requestGroup.getName(), requestGroup.getDescription())
            );
        } catch (Exception e) {
            log.error("Error updating group {}: {}", id, e.getMessage());
            throw e;
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
        try {
            requestGroupService.deleteGroup(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            log.error("Error deleting group {}: {}", id, e.getMessage());
            throw e;
        }
    }

    @PutMapping("/{id}/rename")
    public ResponseEntity<RequestGroup> renameGroup(@PathVariable Long id, @RequestBody Map<String, String> request) {
        try {
            String newName = request.get("name");
            if (newName == null || newName.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }

            return ResponseEntity.ok(requestGroupService.updateGroup(id, newName.trim(), null));
        } catch (Exception e) {
            log.error("Error renaming group {}: {}", id, e.getMessage());
            throw e;
        }
    }

    @GetMapping("/simple")
    public ResponseEntity<List<Map<String, Object>>> getSimpleGroups(@RequestParam Long projectId) {
        try {
            Project project = projectRepository.findById(projectId)
                    .orElseThrow(() -> new RuntimeException("Project not found"));
            
            List<RequestGroup> groups = requestGroupService.getGroupsByProjectId(projectId);
            List<Map<String, Object>> simpleGroups = groups.stream()
                .map(group -> {
                    Map<String, Object> simpleGroup = new HashMap<>();
                    simpleGroup.put("id", group.getId());
                    simpleGroup.put("name", group.getName());
                    return simpleGroup;
                })
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(simpleGroups);
        } catch (Exception e) {
            log.error("Error getting simple groups: ", e);
            throw e;
        }
    }
} 